#include "Sprite.h"

#pragma comment(lib,"d3dx9.lib")

Sprite::Sprite(LPD3DXSPRITE SpriteHandler,Texture *texture, float Width, float Height, int SpritePerRow ,int StartIndex )
{
	_Texture = texture;
	_SpriteHandler = SpriteHandler;
	_Width = Width;
	_Height=Height;
	_SpritePerRow=SpritePerRow;
	_Index = _StartIndex=StartIndex;
}

Sprite::~Sprite(void){}

void Sprite::Render(LPDIRECT3DSURFACE9 Target, int xCenter, int yCenter, int alpha, float xScale, float yScale, ViewPort *viewport)
{
	RECT sRect;
	sRect.left = (_Index % _SpritePerRow) * _Width;
	sRect.top = (_Index / _SpritePerRow) * _Height;
	sRect.right = sRect.left + _Width;
	sRect.bottom = sRect.top + _Height;

	D3DXMATRIX idenMatrix;
	D3DXMatrixIdentity(&idenMatrix);
	idenMatrix._22=-1;
	D3DXVECTOR4 vppos;
	D3DXVECTOR3 temp(-viewport -> getLeft() + xCenter, -viewport -> getBottom() + yCenter,(float)0);
	D3DXVec3Transform(&vppos,&temp,&idenMatrix);

	D3DXVECTOR3 position((float)vppos.x - _Width/2, (float)vppos.y - _Height/2, 0);

	//Flip left or not
	D3DXMATRIX transform; 
	D3DXMatrixTransformation2D(&transform, 
		&D3DXVECTOR2(-viewport -> getLeft() + xCenter, -viewport -> getBottom() + yCenter), 
		0, 
		&D3DXVECTOR2(xScale, yScale), 
		&D3DXVECTOR2((float)xCenter,(float)yCenter),//NULL 
		0, 
		&D3DXVECTOR2(0,0)); 
	_SpriteHandler->SetTransform(&transform); 

	_SpriteHandler -> Draw(_Texture -> GetImage(), 
		&sRect, 
		NULL, 
		&position, 
		D3DCOLOR_ARGB(alpha,255,255,255)
		);
}

float Sprite::GetWidth()
{
	return _Width;
}
float Sprite::GetHeight()
{
	return _Height;
}